import requests
from DrissionPage._pages.chromium_page import ChromiumPage
from DrissionPage._units.actions import Actions
import time
import random
import os
import hashlib
from pathlib import Path

from 小红书 import 图片去水印


# 生成图片的md5
def calculate_md5(content):
    return hashlib.md5(content).hexdigest()


# 图片是否重复
def is_image_unique(save_dir, image_md5):
    # 检查是否已存在相同 MD5 的图片
    for existing_file in Path(save_dir).glob("*"):
        if existing_file.is_file():
            with open(existing_file, "rb") as f:
                existing_md5 = calculate_md5(f.read())
            if existing_md5 == image_md5:
                print(f"重复图片已跳过：{save_dir}（MD5: {image_md5}）")
                return False
    return True

if not os.path.exists('img'):
    os.mkdir('img')

random_float = round(random.uniform(1.0, 1.5), 2)
print(random_float)

headers = {
    "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
    "referer":"https://www.xiaohongshu.com/"
}

# 打开网页
page = ChromiumPage()
ac = Actions(page)
page.listen.start("/web/v1/search/notes")
page.get("https://www.xiaohongshu.com/search_result/?keyword=%25E7%258C%25AB%25E5%2592%258C%25E8%2580%2581%25E9%25BC%25A0%25E8%25A1%25A8%25E6%2583%2585%25E5%258C%2585&source=web_explore_feed&type=51")
count = 1
for i in range(10):
    res = page.listen.wait()
    body = res.response.body
    # 当前页列表数据
    items = body['data']['items']
    # 等待1-1.5秒
    time.sleep(round(random.uniform(1.0, 1.5), 2))
    if items:
        for item in items:
            if 'note_card' in item:
                note_card = item['note_card']
                if 'display_title' in note_card:
                    # 笔记标题
                    note_title = note_card['display_title']
                    if 'image_list' in note_card:
                        # 笔记下的所有表情包
                        image_list = note_card['image_list']
                        for image in image_list:
                            if 'info_list' in image:
                                # 单张表情包图片
                                pic = image['info_list'][0]
                                # 表情包url地址
                                picUrl= pic['url']
                                # 表情包图片名称
                                imgName = picUrl.split('/')[-1]
                                pic_res = requests.get(picUrl)
                                pic_md5 = calculate_md5(pic_res.content)
                                flag = is_image_unique("img", pic_md5)
                                if flag:
                                    # 下载表情包图片
                                    with open('img/' + imgName + '.jpg', 'wb') as f:
                                        f.write(图片去水印.remove_watermarks_in_memory(pic_res.content))
                                        print(str(count) + "_" + note_title + "_" + imgName)
                                        count += 1
    ac.scroll(delta_y=1500)
    print("滚动了一次")

